<template>
  <header class="home-header" :class="{ 'scrolled': isScrolled }">
    <div class="header-container">
      <!-- Logo -->
      <div class="header-logo" @click="goHome">
        <div class="logo-text-main">ZenithMind</div>
      </div>

      <!-- 导航菜单 -->
      <nav class="header-nav" v-if="!isMobile">
        <div class="nav-menu">
          <div 
            v-for="item in navItems" 
            :key="item.key"
            class="nav-item"
            :class="{ 'active': activeNav === item.key }"
            @click="handleNavClick(item)"
            @mouseenter="showSubmenu(item)"
            @mouseleave="hideSubmenu"
          >
            <span>{{ item.label }}</span>
            <el-icon v-if="item.children"><ArrowDown /></el-icon>
            
            <!-- 子菜单 -->
            <div 
              v-if="item.children && submenuVisible === item.key" 
              class="submenu"
              @mouseenter="keepSubmenu"
              @mouseleave="hideSubmenu"
            >
              <div 
                v-for="child in item.children" 
                :key="child.key"
                class="submenu-item"
                @click.stop="handleNavClick(child)"
              >
                <el-icon v-if="child.icon">
                  <component :is="child.icon" />
                </el-icon>
                <div class="submenu-content">
                  <div class="submenu-title">{{ child.label }}</div>
                  <div class="submenu-desc">{{ child.description }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </nav>

      <!-- 用户操作区 -->
      <div class="header-actions">
        <!-- 搜索 -->
        <div class="search-container" v-if="!isMobile">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索课程、资讯..."
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 主题切换 -->
        <el-tooltip content="切换主题" placement="bottom">
          <el-button 
            circle 
            @click="toggleTheme"
            class="theme-btn"
          >
            <el-icon>
              <Sunny v-if="!isDark" />
              <Moon v-else />
            </el-icon>
          </el-button>
        </el-tooltip>

        <!-- 通知 -->
        <el-badge 
          v-if="userStore.isLoggedIn" 
          :value="unreadCount" 
          :hidden="unreadCount === 0"
          class="notification-badge"
        >
          <el-button circle @click="showNotifications">
            <el-icon><Bell /></el-icon>
          </el-button>
        </el-badge>

        <!-- 用户菜单 -->
        <div v-if="userStore.isLoggedIn" class="user-menu">
          <el-dropdown @command="handleUserCommand" trigger="click">
            <div class="user-avatar">
              <el-avatar :src="userStore.userAvatar" :size="36">
                {{ userStore.userName.charAt(0) }}
              </el-avatar>
              <span v-if="!isMobile" class="user-name">{{ userStore.userName }}</span>
              <el-icon><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="dashboard">
                  <el-icon><User /></el-icon>
                  学习中心
                </el-dropdown-item>
                <el-dropdown-item command="profile">
                  <el-icon><Setting /></el-icon>
                  个人资料
                </el-dropdown-item>
                <el-dropdown-item command="settings">
                  <el-icon><Tools /></el-icon>
                  系统设置
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 登录/注册按钮 -->
        <div v-else class="auth-buttons">
          <el-button @click="goLogin" class="login-btn">登录</el-button>
          <el-button type="primary" @click="goRegister" class="register-btn">注册</el-button>
        </div>

        <!-- 移动端菜单按钮 -->
        <el-button 
          v-if="isMobile" 
          circle 
          @click="toggleMobileMenu"
          class="mobile-menu-btn"
        >
          <el-icon><Menu /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 移动端菜单 -->
    <div v-if="isMobile && mobileMenuVisible" class="mobile-menu">
      <div class="mobile-nav">
        <div 
          v-for="item in navItems" 
          :key="item.key"
          class="mobile-nav-item"
          @click="handleMobileNavClick(item)"
        >
          <span>{{ item.label }}</span>
          <el-icon v-if="item.children"><ArrowRight /></el-icon>
        </div>
      </div>
      
      <div class="mobile-search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程、资讯..."
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <div v-if="!userStore.isLoggedIn" class="mobile-auth">
        <el-button @click="goLogin" class="mobile-login-btn">登录</el-button>
        <el-button type="primary" @click="goRegister" class="mobile-register-btn">注册</el-button>
      </div>
    </div>

    <!-- 通知抽屉 -->
    <NotificationDrawer 
      v-model="notificationVisible" 
      @update-count="updateNotificationCount"
    />
  </header>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useThemeStore } from '@/stores/theme'
import { useAppStore } from '@/stores/app'
import { 
  Search, Bell, User, Setting, Tools, SwitchButton, Menu,
  ArrowDown, ArrowRight, Sunny, Moon
} from '@element-plus/icons-vue'
import NotificationDrawer from '@/components/common/NotificationDrawer.vue'

const router = useRouter()
const userStore = useUserStore()
const themeStore = useThemeStore()
const appStore = useAppStore()

// 响应式数据
const isScrolled = ref(false)
const activeNav = ref('home')
const submenuVisible = ref('')
const searchKeyword = ref('')
const mobileMenuVisible = ref(false)
const notificationVisible = ref(false)
const unreadCount = ref(0)
const hideSubmenuTimer = ref(null)

// 计算属性
const isMobile = computed(() => appStore.isMobile)
const isDark = computed(() => themeStore.isDark)

// 导航菜单配置
const navItems = ref([
  {
    key: 'home',
    label: '首页',
    route: '/'
  },
  {
    key: 'learn',
    label: '学习',
    children: [
      {
        key: 'classroom',
        label: '智能课堂',
        description: '在线视频学习，智能推荐',
        icon: 'VideoPlay',
        route: '/classroom'
      },
      {
        key: 'exam',
        label: '在线考试',
        description: '智能组卷，实时评分',
        icon: 'EditPen',
        route: '/exam'
      },
      {
        key: 'coding',
        label: '编程实战',
        description: '在线编程，代码评测',
        icon: 'Monitor',
        route: '/coding'
      },
      {
        key: 'task',
        label: '学习任务',
        description: '任务管理，进度跟踪',
        icon: 'List',
        route: '/task'
      }
    ]
  },
  {
    key: 'resources',
    label: '资源',
    children: [
      {
        key: 'library',
        label: '数字图书馆',
        description: '海量图书，在线阅读',
        icon: 'Reading',
        route: '/library'
      },
      {
        key: 'documents',
        label: '文档中心',
        description: '学习资料，文档管理',
        icon: 'Document',
        route: '/documents'
      },
      {
        key: 'disk',
        label: '云端网盘',
        description: '文件存储，资源共享',
        icon: 'FolderOpened',
        route: '/disk'
      }
    ]
  },
  {
    key: 'community',
    label: '社区',
    children: [
      {
        key: 'chat',
        label: '学习交流',
        description: '实时聊天，群组讨论',
        icon: 'ChatDotRound',
        route: '/chat'
      },
      {
        key: 'blog',
        label: '技术博客',
        description: '分享心得，技术交流',
        icon: 'Edit',
        route: '/blog'
      },
      {
        key: 'notes',
        label: '学习笔记',
        description: '记录笔记，知识整理',
        icon: 'Notebook',
        route: '/notes'
      }
    ]
  },
  {
    key: 'tools',
    label: '工具',
    children: [
      {
        key: 'ai-chat',
        label: 'AI助手',
        description: '智能问答，学习辅导',
        icon: 'ChatDotRound',
        route: '/ai-chat'
      },
      {
        key: 'version',
        label: '版本控制',
        description: '代码管理，项目协作',
        icon: 'Connection',
        route: '/version'
      },
      {
        key: 'mall',
        label: '学习商城',
        description: '课程购买，学习资源',
        icon: 'ShoppingCart',
        route: '/mall'
      }
    ]
  },
  {
    key: 'news',
    label: '资讯',
    route: '/news'
  }
])

// 方法
const handleScroll = () => {
  isScrolled.value = window.scrollY > 50
}

const goHome = () => {
  router.push('/')
  activeNav.value = 'home'
}

const handleNavClick = (item) => {
  if (item.route) {
    router.push(item.route)
    activeNav.value = item.key
    hideSubmenu()
  }
}

const handleMobileNavClick = (item) => {
  if (item.route) {
    router.push(item.route)
    mobileMenuVisible.value = false
  } else if (item.children) {
    // 处理移动端子菜单
    // 可以展开子菜单或跳转到专门的子菜单页面
  }
}

const showSubmenu = (item) => {
  if (item.children) {
    // 清除任何现有的隐藏定时器
    if (hideSubmenuTimer.value) {
      clearTimeout(hideSubmenuTimer.value)
      hideSubmenuTimer.value = null
    }
    submenuVisible.value = item.key
  }
}

const hideSubmenu = () => {
  // 使用变量存储定时器ID
  hideSubmenuTimer.value = setTimeout(() => {
    submenuVisible.value = ''
    hideSubmenuTimer.value = null
  }, 300)
}

const keepSubmenu = () => {
  // 保持子菜单显示，取消任何可能的隐藏定时器
  if (hideSubmenuTimer.value) {
    clearTimeout(hideSubmenuTimer.value)
    hideSubmenuTimer.value = null
  }
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value }
    })
    mobileMenuVisible.value = false
  }
}

const toggleTheme = () => {
  themeStore.setTheme(themeStore.isDark ? 'light' : 'dark')
}

const toggleMobileMenu = () => {
  mobileMenuVisible.value = !mobileMenuVisible.value
}

const showNotifications = () => {
  notificationVisible.value = true
}

const updateNotificationCount = (count) => {
  unreadCount.value = count
}

const handleUserCommand = (command) => {
  switch (command) {
    case 'dashboard':
      router.push('/dashboard')
      break
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      userStore.logout().then(() => {
        router.push('/')
      })
      break
  }
}

const goLogin = () => {
  router.push('/login')
  mobileMenuVisible.value = false
}

const goRegister = () => {
  router.push('/register')
  mobileMenuVisible.value = false
}

onMounted(() => {
  window.addEventListener('scroll', handleScroll)
  
  // 初始化通知数量
  if (userStore.isLoggedIn) {
    // 获取未读通知数量
    // notificationApi.getUnreadCount().then(res => {
    //   unreadCount.value = res.data
    // })
  }
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style lang="scss" scoped>
.home-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: #6675f7;
  transition: all 0.3s ease;
  
  &.scrolled {
    background: #6675f7;
    box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
    
    .header-logo .logo-text-main,
    .nav-item {
      color: white;
    }
  }
  
  .header-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.header-logo {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  margin-right: 20px;
  
  .logo-text-main {
    font-size: 1.5rem;
    font-weight: 700;
    color: white;
    transition: color 0.3s ease;
  }
}

.header-nav {
  flex: 1;
  display: flex;
  justify-content: flex-start;
  
  .nav-menu {
    display: flex;
    gap: 10px;
  }
  
  .nav-item {
    position: relative;
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 8px 16px;
    color: white;
    cursor: pointer;
    border-radius: 4px;
    transition: all 0.3s ease;
    
    &:hover {
      background: rgba(255, 255, 255, 0.2);
    }
    
    &.active {
      background: rgba(255, 255, 255, 0.3);
    }
  }
  
  .submenu {
    position: absolute;
    top: calc(100% - 5px);
    left: 0;
    min-width: 280px;
    background: white;
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    padding: 12px;
    margin-top: 5px;
    z-index: 1001;
    
    &::before {
      content: '';
      position: absolute;
      top: -15px;
      left: 0;
      right: 0;
      height: 15px;
      background: transparent;
    }
    
    .submenu-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 12px;
      border-radius: 8px;
      cursor: pointer;
      transition: background 0.2s ease;
      
      &:hover {
        background: var(--el-bg-color-page);
      }
      
      .submenu-content {
        .submenu-title {
          font-weight: 500;
          color: var(--el-text-color-primary);
          margin-bottom: 4px;
        }
        
        .submenu-desc {
          font-size: 0.8rem;
          color: var(--el-text-color-secondary);
        }
      }
    }
  }
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
  
  .search-container {
    .search-input {
      width: 240px;
      
      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.2);
        border: none;
        border-radius: 18px;
        box-shadow: none;
        
        .el-input__inner {
          color: white;
          
          &::placeholder {
            color: rgba(255, 255, 255, 0.8);
          }
        }
        
        .el-input__prefix {
          color: white;
          opacity: 0.8;
        }
      }
    }
  }
  
  .theme-btn {
    background: rgba(255, 255, 255, 0.2);
    border: none;
    color: white;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
  
  .user-menu {
    .user-avatar {
      display: flex;
      align-items: center;
      gap: 8px;
      cursor: pointer;
      
      .user-name {
        color: white;
        font-weight: 500;
      }
    }
  }
  
  .auth-buttons {
    display: flex;
    gap: 12px;
    
    .login-btn {
      background: transparent;
      border: 1px solid rgba(255, 255, 255, 0.5);
      color: white;
      border-radius: 18px;
      
      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }
    }
    
    .register-btn {
      background: white;
      color: #6675f7;
      border: none;
      border-radius: 18px;
      
      &:hover {
        background: rgba(255, 255, 255, 0.9);
      }
    }
  }
}

// 移动端样式
.mobile-menu {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border-top: 1px solid var(--el-border-color);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  
  .mobile-nav {
    padding: 20px;
    
    .mobile-nav-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 16px 0;
      border-bottom: 1px solid var(--el-border-color-lighter);
      cursor: pointer;
      
      &:last-child {
        border-bottom: none;
      }
    }
  }
  
  .mobile-search {
    padding: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
  }
  
  .mobile-auth {
    padding: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
    display: flex;
    gap: 12px;
    
    .mobile-login-btn,
    .mobile-register-btn {
      flex: 1;
    }
  }
}

@media (max-width: 768px) {
  .header-container {
    padding: 0 16px;
  }
  
  .header-actions .search-container {
    display: none;
  }
}
</style>
